
import { loginApi } from "@/http/userApi/loginApi"

export default {
    namespaced: true,
    state: {
        token: JSON.parse(localStorage.userInfo || "{}").token,
        userId: JSON.parse(localStorage.userInfo || "{}").userId,
        username: JSON.parse(localStorage.userInfo || "{}").username,
        role: JSON.parse(localStorage.userInfo || "[]").role,
        addRoute: JSON.parse(localStorage.addRoute || "[]"),
        btnPermission: []
    },
    mutations: {
        setUser(state, user) {
            state.token = user.token;
            state.userId = user.userId;
            state.username = user.username;
            state.role = user.role
        },
        setAddRoute(state, route) {
            console.log(route)
            localStorage.addRoute = JSON.stringify(route)
            state.addRoute = route
        },
        quitSys(state) {
            state.token = "";
            state.userId = "";
            state.username = "";
            state.role = ""
            localStorage.clear();
            sessionStorage.clear();
            window.location.href = "/login"
        }
    },
    actions: {
        async loginTo({ commit }, { pwd, phone }) {
            try {
                let userData = await loginApi({ pwd, phone })
                console.log(userData)
                if (userData.data.code == 200) {
                    let obj = {
                        token: userData.data.token,
                        userId: userData.data.data.id,
                        username: userData.data.data.username,
                        role: userData.data.data.position
                    }
                    console.log(userData.data.data.position)
                    localStorage.userInfo = JSON.stringify(obj)
                    commit("setUser", obj)
                    return Promise.resolve()
                } else {
                    return Promise.reject(userData.data)
                }
            }
            catch (e) {
                return Promise.reject(e)
            }
        }

    }
}